package com.bims.jreport.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson.JSON;
import com.bims.jreport.document.DocTemplate;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.pdfa.PdfADocument;

import java.io.ByteArrayOutputStream;
import java.util.List;

import static com.bims.jreport.constant.ReportConstants.DEFAULT_PDF_PAGE_INDEX;
import static com.bims.jreport.constant.ReportConstants.INTENT;

/**
 * 文档工具类
 *
 * @author wangrenjie
 */
public class DocumentUtil {


    public static DocTemplate getDocTemplate(String json) {
        return JSON.parseObject(json, DocTemplate.class);
    }



    /**
     * 合并
     *
     * @param documents 多个PDF文档
     * @return 合并后的单个文档
     */
    public static PdfDocument merge(List<PdfDocument> documents) {
        PdfADocument document = creatPdfDocument();
        document.initializeOutlines();
        for (PdfDocument doc : documents) {
            PdfPageFormCopier pageFormCopier = new PdfPageFormCopier();
            doc.copyPagesTo(DEFAULT_PDF_PAGE_INDEX, doc.getNumberOfPages(), document, pageFormCopier);
            doc.close();
        }
        //TODO 暂时先看看关闭会不会有异常
        document.close();
        return document;
    }


    /**
     * 创建Pdf/A文档
     *
     * @return PdfADocument
     */
    public static PdfADocument creatPdfDocument() {
        WriterProperties writerProperties = new WriterProperties();
        //体积优化模式
        writerProperties.useSmartMode();
        //调试模式
        writerProperties.useDebugMode();
        //PDF
        PdfWriter pdfWriter = new PdfWriter(new ByteArrayOutputStream(), writerProperties);
        //文档配置
        StampingProperties stampingProperties = new StampingProperties();
        //追加模式--->一步一签
        stampingProperties.useAppendMode();
        PdfOutputIntent pdfOutputIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", ResourceUtil.getStream(INTENT));
        PdfADocument document = new PdfADocument(pdfWriter, PdfAConformanceLevel.PDF_A_3A, pdfOutputIntent, stampingProperties);
        //设置PDF/A必须的配置
        document.setTagged();
        document.getCatalog().setLang(new PdfString("en-US"));
        document.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
        return document;
    }

}
